//跟进统计表
var $dataInfo = $('#followTable');
//防止表头与表格不对齐
$(window).resize(function () {
    $dataInfo.bootstrapTable('resetView');
});

$(function () {

    //初始化跟进统计表
    initFollowTableData();

    polyLineInitData();//折线图数据初始化
    mapInitData();//地图初始化
    histogramInitData();//柱状图初始化

    $('#typeSelect').selectpicker();
})

//柱状图初始化
function histogramInitData() {
    $.ajax({
        url: "/customerStatistics/getCustomerBusiness",
        async: true,
        type: "POST",
        dataType: "json",
        success: function (result) {
            if (result.code == "000000") {
                console.log(result.data)
                histogramInit('histogram', result.data.histogram);      // 柱状图
                var percentageData = result.data.percentage.split('/');
                $('#percentage').html(percentageData[0]);
                $('#percentageTotal').html(percentageData[1]);
                $('#hasNotOpportunity').html(result.data.hasNotOpportunity);
            }
        },
        error: function (res) {
            alert('请求失败')
        }
    })
}

//折线图数据初始化
function polyLineInitData() {
    var myChart = echarts.init(document.getElementById('polyLine'));
    myChart.showLoading();  // echarts加载动画

    $.ajax({
        url: "/customerStatistics/getPolyLine",
        async: true,
        data: queryParamsForLine(),
        type: "POST",
        dataType: "json",
        success: function (result) {
            if (result.code == "000000") {
                polyLineInit('polyLine', result.data);      //折线图
            }
        },
        error: function (res) {
            alert('请求失败')
        }
    })
}

// 地图初始化
function mapInitData() {
    // var type = $('#mapTypeSelect option:selected').val();
    $.ajax({
        url: "/customerStatistics/getMapData",
        // url: "/customerStatistics/getMapData?type=" + type,
        async: true,
        type: "POST",
        dataType: "json",
        success: function (result) {
            if (result.code == "000000") {
                initMap('main', result.data)
            }
        },
        error: function (res) {
            alert('请求失败')
        }
    })
}

//初始化表格
function initFollowTableData() {
//先销毁表格
    $dataInfo.bootstrapTable('destroy');
    $dataInfo.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/customerStatistics/getCustomerFollow',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        // sortOrder: "desc",//排序方式
        // sortName: 'num',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: false,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        // sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        // pageSize: 10,//每页的记录行数
        // pageNumber: 1,//初始化加载第1页，默认第1页
        // pageList: "[5]",//可供选择的每页的行数
        queryParams: queryParamsForTable,
        columns: [
            {title: '客户名称', field: 'customerName', align: 'left', valign: 'middle'},
            {title: '所有人', field: 'userName', align: 'left', valign: 'middle'},
            {title: '跟进次数', field: 'num', align: 'left', valign: 'middle'},
            {title: '意向值', field: 'customerIntention', align: 'left', valign: 'middle'}
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadError: function (status) {

            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

/**
 * 折线图查询参数
 */
function queryParamsForLine() {
    var param = {};
    //搜索条件
    param.dateUnit = $("#dateUnit").val();  //上年1 本年2 本周3 本月4 上月5
    return param;
}

/**
 * 表格查询参数
 * @param params
 */
function queryParamsForTable(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式

    params.dateUnit = $('#dateUnitForTable').val();
    params.type = $('#typeSelect option:selected').val();
    return params;
}

/**
 * 上年 本年 本周 本月 上月切换
 * @param time
 */
function selectTime(time) {
    if (time == 'lastYear') {//上年
        $('#dateUnit1').addClass('active-second');
        $('#dateUnit2').removeClass('active-second');
        $('#dateUnit3').removeClass('active-second');
        $('#dateUnit4').removeClass('active-second');
        $('#dateUnit5').removeClass('active-second');
        $("#dateUnit").val(1);
    }
    if (time == 'year') {//本年
        $('#dateUnit1').removeClass('active-second');
        $('#dateUnit2').addClass('active-second');
        $('#dateUnit3').removeClass('active-second');
        $('#dateUnit4').removeClass('active-second');
        $('#dateUnit5').removeClass('active-second');
        $("#dateUnit").val(2);
    }
    if (time == 'week') {//本周
        $('#dateUnit1').removeClass('active-second');
        $('#dateUnit2').removeClass('active-second');
        $('#dateUnit3').addClass('active-second');
        $('#dateUnit4').removeClass('active-second');
        $('#dateUnit5').removeClass('active-second');
        $("#dateUnit").val(3);
    }
    if (time == 'month') {//本月
        $('#dateUnit1').removeClass('active-second');
        $('#dateUnit2').removeClass('active-second');
        $('#dateUnit3').removeClass('active-second');
        $('#dateUnit4').addClass('active-second');
        $('#dateUnit5').removeClass('active-second');
        $("#dateUnit").val(4);
    }
    if (time == 'lastMonth') {//上月
        $('#dateUnit1').removeClass('active-second');
        $('#dateUnit2').removeClass('active-second');
        $('#dateUnit3').removeClass('active-second');
        $('#dateUnit4').removeClass('active-second');
        $('#dateUnit5').addClass('active-second');
        $("#dateUnit").val(5);
    }
    polyLineInitData();//折线图数据初始化
}


/**
 * 全部 本年 本周 本月 上月切换
 * @param time
 */
function selectTimeForTable(time) {
    if (time == 'all') {//全部
        $('#dateUnitForTable1').addClass('active-second');
        $('#dateUnitForTable2').removeClass('active-second');
        $('#dateUnitForTable3').removeClass('active-second');
        $('#dateUnitForTable4').removeClass('active-second');
        $('#dateUnitForTable5').removeClass('active-second');
        $("#dateUnitForTable").val(1);
    }
    if (time == 'week') {//本周
        $('#dateUnitForTable1').removeClass('active-second');
        $('#dateUnitForTable2').addClass('active-second');
        $('#dateUnitForTable3').removeClass('active-second');
        $('#dateUnitForTable4').removeClass('active-second');
        $('#dateUnitForTable5').removeClass('active-second');
        $("#dateUnitForTable").val(2);
    }
    if (time == 'lastMonth') {//上月
        $('#dateUnitForTable1').removeClass('active-second');
        $('#dateUnitForTable2').removeClass('active-second');
        $('#dateUnitForTable3').addClass('active-second');
        $('#dateUnitForTable4').removeClass('active-second');
        $('#dateUnitForTable5').removeClass('active-second');
        $("#dateUnitForTable").val(3);
    }
    if (time == 'month') {//本月
        $('#dateUnitForTable1').removeClass('active-second');
        $('#dateUnitForTable2').removeClass('active-second');
        $('#dateUnitForTable3').removeClass('active-second');
        $('#dateUnitForTable4').addClass('active-second');
        $('#dateUnitForTable5').removeClass('active-second');
        $("#dateUnitForTable").val(4);
    }
    if (time == 'year') {//本年
        $('#dateUnitForTable1').removeClass('active-second');
        $('#dateUnitForTable2').removeClass('active-second');
        $('#dateUnitForTable3').removeClass('active-second');
        $('#dateUnitForTable4').removeClass('active-second');
        $('#dateUnitForTable5').addClass('active-second');
        $("#dateUnitForTable").val(5);
    }
    $dataInfo.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParamsForTable});
}

//选择筛选条件时重新加载表格
function selectOnchang() {
    $dataInfo.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParamsForTable});
}

//选择筛选条件时重新加载地图数据
function mapTypeSelectOnchang() {
    mapInitData();//地图初始化
}

/**
 * 折线图初始化
 */
function polyLineInit(id, data) {
    let dom = document.getElementById(id);
    let myChart = echarts.init(dom);
    let option = {
        title: {
            text: ''
        },
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            top: 10,
            data: ['客户总数', '意向客户', '会员客户', '成交客户', '无意向客户', '新单客户', '续费客户']
        },
        grid: {
            left: '10',
            right: '36',
            bottom: '20',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: data.time,
            axisTick: {
                show: false
            },
            axisLine: {
                lineStyle: {
                    color: '#eeeeee',
                    width: 1 //这里是为了突出显示加上的
                }
            },
            axisLabel: {
                textStyle: {
                    color: '#999',
                    fontSize: 12,
                    padding: [10, 0, 0, 0]
                }
            }
        },
        yAxis: {
            type: 'value',
            minInterval: 1,
            axisTick: {
                show: false
            },
            axisLine: {
                lineStyle: {
                    color: 'rgba(255, 129, 109, 0.1)',
                    width: 0 //这里是为了突出显示加上的
                }
            },
            axisLabel: {
                textStyle: {
                    color: '#999',
                    padding: [0, 10, 0, 0]
                }
            },
            splitArea: {
                areaStyle: {
                    color: 'rgba(255,255,255,.5)'
                }
            },
            splitLine: {
                show: true,
                lineStyle: {
                    color: '#eee',
                    width: 1,
                    type: 'dashed'
                }
            }
        },
        color: [
            '#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452'
        ],
        series: [
            {
                name: '客户总数',
                type: 'line',
                data: data.sum
            },
            {
                name: '意向客户',
                type: 'line',
                data: data.intention
            },
            {
                name: '会员客户',
                type: 'line',
                data: data.member
            },
            {
                name: '成交客户',
                type: 'line',
                data: data.deal
            },
            {
                name: '无意向客户',
                type: 'line',
                data: data.noIntention
            },
            {
                name: '新单客户',
                type: 'line',
                data: data.new
            },
            {
                name: '续费客户',
                type: 'line',
                data: data.renew
            }
        ]
    };

    myChart.setOption(option);
    myChart.hideLoading();  // 获取数据后关闭加载动画
    window.addEventListener("resize", function () {
        myChart.resize();
    });
    return myChart;
}

//柱状图初始化
function histogramInit(id, data) {
    let dom = document.getElementById(id);
    let myChart = echarts.init(dom);
    let option = {
        // title: {text: '客户商机分层'},
        tooltip: {
            trigger: 'axis',
            axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
            }
        },
        grid: {
            x: '10',
            x2: '40',
            y: '10',
            y2: '0',
            containLabel: true
        },
        yAxis: {
            type: 'category',
            axisLine: {
                show: false
            },
            axisTick: {
                show: false
            },
            axisLabel: {
                color: '#999',
                padding: [0, 8, 0, 0]
            },
            splitLine: {
                show: false,
            },
            data: ['初步洽谈', '需求确定', '方案报价', '谈判', '洽谈合同', '赢单', '输单'],
        },
        xAxis: {
            show: false
        },
        color: [
            '#5470c6'
        ],
        series: [{
            type: 'bar',
            name: '客户个数',
            showBackground: true,
            backgroundStyle: {
                borderRadius: 30,
                color: '#f4f8ff',
            },
            itemStyle: {
                normal: {
                    barBorderRadius: 30,
                    color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [{
                        offset: 0,
                        color: '#5977ff'
                    }, {
                        offset: 1,
                        color: '#5977ff'
                    }]),
                },
            },
            barWidth: 13,
            label: {
                show: true,
                precision: 1,
                position: 'right',
                padding: [2, 0, 0, 6],
                valueAnimation: true,
                color: '#5977ff'
            },
            data: data,
        }]
    };

    myChart.setOption(option);
    window.addEventListener("resize", function () {
        myChart.resize();
    });
}

//地图初始化
function initMap(id, data) {
    console.log(data)
    let dom = document.getElementById(id);
    let myChart = echarts.init(dom);
    let option = {
        title: [
            {
                show: false,
                text: '客户区域分布图',
            },
        ],
        tooltip: {
            trigger: 'item',
        },
        color: [
            '#5470c6', '#91cc75', '#fac858'
        ],
        legend: {
            show: true,
        },
        visualMap: {
            type: 'continuous',
            min: 0,
            max: 200,
            seriesIndex: [0, 2],
            dimension: 0,
            realtime: false,
            left: 0,
            itemWidth: 18,
            itemHeight: 100,
            calculable: true,
            inRange: {
                color: ['rgba(159,205,253,0.50)', '#60ACFC'],
                symbolSize: [100, 100]
            },
            outOfRange: {
                color: ['#eeeeee'],
                symbolSize: [100, 100]
            },
        },
        series: [
            {
                name: '会员客户',
                type: 'map',
                mapType: 'china',
                roam: 'move',
                mapValueCalculation: 'sum',
                zoom: 1,
                selectedMode: false,
                showLegendSymbol: false,
                label: {
                    normal: {
                        textStyle: {
                            color: '#666',
                        },
                    },
                    emphasis: {
                        textStyle: {
                            color: '#234EA5',
                        },
                    },
                },
                itemStyle: {
                    normal: {
                        areaColor: '#EEEEEE',
                        borderColor: '#FFFFFF',
                    },
                    emphasis: {
                        areaColor: '#E5F39B',
                    },
                },
                data: data.member,
            },{
                name: '非会员客户',
                type: 'map',
                mapType: 'china',
                roam: 'move',
                mapValueCalculation: 'sum',
                zoom: 1,
                selectedMode: false,
                showLegendSymbol: false,
                label: {
                    normal: {
                        textStyle: {
                            color: '#666',
                        },
                    },
                    emphasis: {
                        textStyle: {
                            color: '#234EA5',
                        },
                    },
                },
                itemStyle: {
                    normal: {
                        areaColor: '#EEEEEE',
                        borderColor: '#FFFFFF',
                    },
                    emphasis: {
                        areaColor: '#E5F39B',
                    },
                },
                data: data.nonMember,
            },{
                name: '未成交客户',
                type: 'map',
                mapType: 'china',
                roam: 'move',
                mapValueCalculation: 'sum',
                zoom: 1,
                selectedMode: false,
                showLegendSymbol: false,
                label: {
                    normal: {
                        textStyle: {
                            color: '#666',
                        },
                    },
                    emphasis: {
                        textStyle: {
                            color: '#234EA5',
                        },
                    },
                },
                itemStyle: {
                    normal: {
                        areaColor: '#EEEEEE',
                        borderColor: '#FFFFFF',
                    },
                    emphasis: {
                        areaColor: '#E5F39B',
                    },
                },
                data: data.nonDeal,
            },
        ],
    };

    myChart.setOption(option);

    window.addEventListener("resize", function () {
        myChart.resize();
    });

}